<template>
  <el-dialog v-model="dialogVisible" :title="titleStr" width="800">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
    >
      <el-form-item label="分数" prop="score">
        <el-input
          v-model="ruleForm.score"
          style="width: 200px"
          @input="handleInput(ruleForm.score, 0)"
        />
        <div class="titleHeader">
          <el-icon>
            <InfoFilled />
          </el-icon>
          分数区间 100-750
        </div>
      </el-form-item>

      <el-form-item
        :label="data.title"
        v-for="(data, index) in xkdata"
        :prop="data.type == 1 ? 'radio' : 'checkbox'"
      >
        <el-radio-group v-if="data.type == 1" v-model="ruleForm.radio">
          <el-radio :label="title" v-for="(id, title, index) in data.item" />
        </el-radio-group>
        <el-checkbox-group
          v-else
          v-model="ruleForm.checkbox"
          :max="data.number"
        >
          <el-checkbox :label="title" v-for="(id, title, index) in data.item" />
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="位次" prop="position">
        <el-input
          v-model="ruleForm.position"
          style="width: 200px"
          @input="handleInput(ruleForm.position, 1)"
        />
        <el-button
          style="margin-left: 10px"
          type="primary"
          @click="queryPosition(ruleFormRef)"
        >
          查询
        </el-button>
        <div style="margin-left: 20px">{{ position }}</div>
      </el-form-item>

      <el-form-item style="display: flex; justify-content: flex-end">
        <el-button @click="closeChange">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          确定
        </el-button>
      </el-form-item>

      <el-form-item style="color: red" v-if="isGKB == '1'">
        <div style="font-size: 18px">
          高考版只能修改一次成绩信息，请谨慎修改！
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import {
  editUser,
  scoreStageInfo,
  scoreStageFilter,
} from '/src/api/appv2/appv2.js';

const emits = defineEmits(['refreshStudentList']);

const dialogVisible = ref(false);
const ruleFormRef = ref(null);
const ruleForm = reactive({
  score: '',
  position: '',
  radio: '',
  checkbox: [],
});
const rules = reactive({
  score: [
    { required: true, message: '请输入分数', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 100 || value > 750) {
          callback(new Error('分数区间 100-750'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  radio: [{ required: true, message: '请选择科类', trigger: 'change' }],
  checkbox: [
    { required: true, message: '请选择科目', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value.length < 2) {
          callback(new Error('请选择两个科目'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
});

// 父级传递的学生数据
const studentData = ref({});
const isGKB = ref('');
// 学生信息
const studentInfo = ref({});
const titleStr = ref('');
const xkdata = ref({}); // 选科科类信息
const position = ref(''); // 位次区间
const filterInfo = ref(null); // 筛选条件

// 只允许输入数字 type 0-分数 1-位次
const handleInput = (score, type) => {
  if (type == 0) {
    ruleForm.score = score.replace(/[^\d]/g, '');
  } else if (type == 1) {
    ruleForm.position = score.replace(/[^\d]/g, '');
  }
};

// 查询位次
function queryPosition(formEl) {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      if (!filterInfo.value) {
        scoreStageFilter({
          studentId: studentData.value.studentId,
          pid: studentInfo.value.pid,
        }).then((res) => {
          filterInfo.value = res.data[0] || {};
          getScoreStageInfo();
        });
      } else {
        getScoreStageInfo();
      }
    }
  });
}

// 查询位次
function getScoreStageInfo() {
  const xk_type = studentInfo.value.xk_type;
  let course = '';

  var body = {
    studentId: studentData.value.studentId,
    pid: studentInfo.value.pid,
    year: filterInfo.value.year,
    score: ruleForm.score,
  };

  if (xk_type == 2) {
    const course = filterInfo.value.courses[0] || {};

    body['bzType'] = course.bzTypes[0] || '';
    body['course'] = course.course;
  } else {
    if (ruleForm.radio == '物理') {
      if (
        filterInfo.value.courses.filter((i) => i.course == ruleForm.radio)
          .length > 0
      ) {
        course =
          filterInfo.value.courses.filter(
            (i) => i.course == ruleForm.radio
          )[0] || {};
      } else {
        course =
          filterInfo.value.courses.filter((i) => i.course == '理科')[0] || {};
      }
    } else if (ruleForm.radio == '历史') {
      if (
        filterInfo.value.courses.filter((i) => i.course == ruleForm.radio)
          .length > 0
      ) {
        course =
          filterInfo.value.courses.filter(
            (i) => i.course == ruleForm.radio
          )[0] || {};
      } else {
        course =
          filterInfo.value.courses.filter((i) => i.course == '文科')[0] || {};
      }
    } else {
      course =
        filterInfo.value.courses.filter((i) => i.course == ruleForm.radio)[0] ||
        {};
    }

    body['bzType'] = course.bzTypes[0] || '';
    body['course'] = course.course;
  }

  scoreStageInfo(body).then((res) => {
    if (res.data.now_section.length == undefined) {
      position.value =
        '位次区间: ' +
        res.data.now_section.highestRank +
        '~' +
        res.data.now_section.lowestRank;
      ruleForm.position = res.data.now_section.lowestRank;
    } else {
      position.value = '';
      ruleForm.position = '';
      ElMessage({
        message: '未查询到位次区间',
        type: 'warning',
      });
    }
  });
}

// 提交表单
function submitForm(formEl) {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let xkInfos = {};
      xkdata.value.forEach((item) => {
        xkInfos = { ...xkInfos, ...item.item };
      });

      if (ruleForm.radio.length > 0) {
        ruleForm.checkbox.push(ruleForm.radio);
      }

      let xkIds = [];
      ruleForm.checkbox.forEach((item) => {
        xkIds.push(xkInfos[item]);
      });
      xkIds = [...new Set(xkIds)];

      let data = {};
      data['studentId'] = studentData.value.studentId;
      data['score'] = ruleForm.score;
      data['section'] = ruleForm.position;
      data['sgid'] = xkIds.toString();
      data['fronttype'] = 3;
      editUser(data).then(() => {
        emits('refreshStudentList', {});
        closeChange();
      });
    }
  });
}

function closeChange() {
  dialogVisible.value = false;
}

function openChange(val) {
  // isGKB.value = isGkData.isGKB
  isGKB.value = val.isGKB;
  dialogVisible.value = true;
  studentData.value = val;
  studentInfo.value = val.student;
  titleStr.value =
    '成绩-' +
    val.studentName +
    '-' +
    val.student.province +
    '-' +
    (val.student.sex == 0 ? '男' : '女');
  ruleForm.score = '';
  ruleForm.position = '';
  ruleForm.radio = '';
  ruleForm.checkbox = [];
  position.value = '';
  filterInfo.value = null;

  if (val.student.xk_type == 1) {
    xkdata.value = [
      {
        type: '1', // 1-单选，2-多选
        title: '选考科目',
        item: {
          文科: '22',
          理科: '11',
        },
      },
    ];
  } else if (val.student.xk_type == 2) {
    xkdata.value = [
      {
        type: '2',
        number: '3',
        title: '选考科目',
        item: {
          物理: '1',
          化学: '2',
          生物: '3',
          政治: '6',
          历史: '4',
          地理: '5',
        },
      },
    ];
  } else {
    xkdata.value = [
      {
        // 单选
        type: '1',
        title: '首选科目',
        item: {
          物理: '1',
          历史: '4',
        },
      },
      {
        // 双选
        type: '2',
        number: '2',
        title: '再选科目',
        item: {
          化学: '2',
          生物: '3',
          政治: '6',
          地理: '5',
        },
      },
    ];
  }

  if (studentInfo.value.pid == '33') {
    // 省ID=33 浙江7选3
    xkdata.value[0]['item']['技术'] = '7';
  }
}

// 暴露方法
defineExpose({
  openChange,
});
</script>
<style lang="scss" scoped>
.titleHeader {
  display: flex;
  align-items: center;
  background-color: #f4f4f5;
  color: #909399;
  margin-left: 20px;
  padding: 0 8px;
}
</style>
